<template>
  <div id="app">
    <MyHeader :addTask="addTask"></MyHeader>
    <MyList :todos="todos"></MyList>
    <MyFooter
      :todos="todos"
      @clearDoneTask="clearDoneTask"
      @changeTaskDoneAll="handleChangeTaskDoneAll"
    ></MyFooter>
  </div>
</template>

<script>
import pubsub from "pubsub-js";

import MyHeader from "./components/MyHeader.vue";
import MyList from "./components/MyList.vue";
import MyFooter from "./components/MyFooter.vue";

export default {
  name: "App",
  data: function () {
    const initTodos = localStorage.getItem("todos");
    return {
      todos: initTodos ? JSON.parse(initTodos) : [],
    };
  },
  watch: {
    todos: {
      deep: true,
      handler(newVal) {
        localStorage.setItem("todos", JSON.stringify(this.todos));
      },
    },
  },
  components: {
    MyHeader,
    MyFooter,
    MyList,
  },
  mounted() {
    // this.$bus.$on("deleteTask", this.deleteTask);
    this.$bus.$on("changeTaskDone", this.changeTaskDone);
    this.pubId = pubsub.subscribe("deleteTask", this.deleteTask);
  },
  beforeDestroy() {
    this.$bus.$off(["deleteTask", "changeTaskDone"]);
    pubsub.unsubscribe(this.pubId);
  },
  methods: {
    addTask(obj) {
      this.todos.unshift(obj);
    },
    deleteTask(_, id) {
      this.todos = this.todos.filter((item) => item.id !== id);
    },
    changeTaskDone(id) {
      this.todos = this.todos.map((item) => {
        if (item.id === id) {
          return { ...item, done: !item.done };
        }
        return item;
      });
    },
    clearDoneTask() {
      this.todos = this.todos.filter((item) => !item.done);
    },
    handleChangeTaskDoneAll(done) {
      this.todos = this.todos.map((item) => {
        return { ...item, done };
      });
    },
  },
};
</script>

<style>
#app {
  width: 400px;
  margin: 40px auto;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 24px 32px 16px 32px;
  font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
input[type="text"] {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
  margin-bottom: 16px;
  box-sizing: border-box;
}
ul {
  list-style: none;
  padding: 0;
  margin: 0 0 16px 0;
}
li {
  display: flex;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}
li:last-child {
  border-bottom: none;
}
input[type="checkbox"] {
  margin-right: 12px;
  width: 18px;
  height: 18px;
}
span {
  flex: 1;
  font-size: 16px;
}
button {
  background: #ff4d4f;
  color: #fff;
  border: none;
  border-radius: 4px;
  padding: 4px 12px;
  cursor: pointer;
  transition: background 0.2s;
  margin-left: 8px;
}
button:hover {
  background: #d9363e;
}
div:last-child {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 12px;
}
div:last-child button {
  background: #1890ff;
}
div:last-child button:hover {
  background: #1765ad;
}
</style>
